package service

import (
	"anban/models"
	"github.com/astaxie/beego/orm"
	"net/url"
	"strconv"
)

type CourseValue struct {
	Id    int64  `json:"id"`
	Value string `json:"value"`
}

// 获取科目信息
func GetCourseInfo(p map[string]interface{}) *models.Course {
	o := orm.NewOrm()
	course := &models.Course{}
	qs := o.QueryTable("Course")
	if _, ok := p["relation"]; ok && p["relation"].(bool) {
		qs = qs.RelatedSel()
	}
	if _, ok := p["id"]; ok {
		qs = qs.Filter("id", p["id"])
	}
	qs.One(course)
	return course
}

// 添加科目信息
func AddCourse(input url.Values) (int64, error) {
	o := orm.NewOrm()
	course := &models.Course{}
	if _, ok := input["name"]; ok {
		course.Name = input["name"][0]
	}
	if _, ok := input["status"]; ok {
		course.Status, _ = strconv.Atoi(input["status"][0])
	}
	return o.Insert(course)
}

// 修改科目信息
func EditCourse(input url.Values) (int64, error) {
	o := orm.NewOrm()
	p := orm.Params{}
	for k, v := range input {
		if k == "id" || k == "_xsrf" {
			continue
		}
		p[k] = v[0]
	}
	return o.QueryTable("Course").Filter("id", input["id"][0]).Update(p)
}

// 获取科目列表
func GetCourseList(p map[string]interface{}) (int64, []*models.Course) {
	var courseList []*models.Course
	o := orm.NewOrm()
	qs := o.QueryTable("Course")
	if _, ok := p["relation"]; ok && p["relation"].(bool) {
		qs = qs.RelatedSel()
	}
	if _, ok := p["status"]; ok {
		qs = qs.Filter("status", p["status"])
	}
	totalCount, _ := qs.Count()
	curPage, ok := p["curPage"]
	perCount, _ := p["perCount"]
	if ok {
		start := perCount.(int) * (curPage.(int) - 1)
		qs = qs.Limit(perCount, start)
	}
	qs.All(&courseList)
	if _, ok := p["convert"]; ok && p["convert"].(bool) {
		for _, course := range courseList {
			course.StatusShow = models.CourseStatus[course.Status]
		}
	}
	return totalCount, courseList
}

func GetCourseListValues(courseList []*models.Course) []*CourseValue {
	data := []*CourseValue{}
	for _, course := range courseList {
		courseVal := &CourseValue{
			Id:    course.Id,
			Value: course.Name,
		}
		data = append(data, courseVal)
	}
	return data
}